package com.ht.demo.service.manager.system.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import com.ht.demo.common.appexception.ResultData;
import com.ht.demo.common.constans.SystemConstant;
import com.ht.demo.common.util.SnowFlakeIdUtil;
import com.ht.demo.service.constans.SystemConfig;
import com.ht.demo.service.manager.system.CaptchaManager;
import com.ht.demo.service.redis.RedisKeyUtil;
import com.ht.demo.service.redis.RedisUtil;
import com.ht.demo.service.redis.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Component
public class CaptchaManagerImpl implements CaptchaManager {
    Logger logger = LoggerFactory.getLogger(CaptchaManagerImpl.class);

    @Resource
    private RedisUtil redisUtil;

    @Override
    public ResultData createCaptcha() {
        ResultData result = new ResultData();
        result.success();
        Boolean enabled = SystemConfig.getCaptchaEnabled();
        result.put("captchaEnabled", enabled);
        if (!enabled) {
            return result;
        }

        // 保存验证码信息
        String uuid = SnowFlakeIdUtil.getSnowFlakeId();
        String redisKey = RedisKeyUtil.CAPTCHA_CODE_KEY + uuid;

        //width height codeCount lineCount(值越高划线越多)
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(SystemConstant.width, SystemConstant.height, SystemConstant.codeCount, SystemConstant.lineCount);
        String code = lineCaptcha.getCode();
        redisUtil.setex(redisKey, code, TimeUtil.MINUTES_5);

        // 转换流信息写出
        BufferedImage image = (BufferedImage) lineCaptcha.createImage(code);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }

        result.put("uuid", uuid);
        result.put("img", Base64.encode(os.toByteArray()));

        logger.info("后台验证码生成成功，uuid={}, code={}", uuid, code);

        return result;
    }
}
